<template>
    <div>
        <el-dialog
            :visible.sync="dialogVisible"
            width="70%"
            :close-on-click-modal="false"
            :before-close="handleClose">
            <el-form ref="form" :model="form" label-width="80px">
                <el-form-item label="文章名称">
                    <el-input v-model="form.name" placeholder="输入文章名称"></el-input>
                </el-form-item>
                <el-form-item v-show="hastype"  label="文章类型">
                    <el-select v-model="form.type" placeholder="文章类型">
                        <el-option v-for="item in options" :label="item.label" :value="item.value" :key="item.index"></el-option>
                        
                    </el-select>
                </el-form-item>
                <el-form-item label="文章上传">
                    <form ref="uploadForm" id="uploadForm" action='upload_file' role="form" method="post" enctype=multipart/form-data>
                        <input type="file" ref="fileUp" name="file" @change="filechange">
                    </form>
                </el-form-item>
                <el-form-item v-show="haskeyword" label="反对意见">
                    <el-checkbox-group v-model="form.keywords">
                        <el-checkbox label="有"></el-checkbox>
                        <el-checkbox label="无"></el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button size="mini" type="primary" @click.prevent="confirmsubmitFile">上 传</el-button>
                <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
            </span>
        </el-dialog>
        <el-row class="topMsg">
            <el-button size="mini" @click="showAddDialog">添加</el-button>
            <div class="rightWay">
                <el-input
                placeholder="输入文章名称"
                size="mini"
                v-model="querydata.search"
                clearable>
                </el-input>
                <el-select width="150" v-model="querydata.article_type" size="mini" clearable placeholder="文章类别">
                    <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                    </el-option>
                </el-select>
                <el-date-picker
                    v-model="querydata.start"
                    type="date"
                    size="mini"
                    placeholder="开始日期"
                    format="yyyy 年 MM 月 dd 日"
                    value-format="yyyy-MM-dd">
                </el-date-picker>
                <el-date-picker
                    v-model="querydata.end"
                    type="date"
                    size="mini"
                    placeholder="结束日期"
                    format="yyyy 年 MM 月 dd 日"
                    value-format="yyyy-MM-dd">
                </el-date-picker>
                <el-button @click="queryReport(1)" class="rightMargin" type="primary" size="mini">搜索</el-button>
            </div>
        </el-row>

        <div>
            <el-table
            :data="tableData"
            border
            style="width: 100%">
            <el-table-column
            fixed
            prop="article_code"
            label="文章ID"
            width="150">
            </el-table-column>
            <el-table-column
            prop="article_name"
            label="文章名称"
            >
            </el-table-column>
            <el-table-column
            prop="create"
            label="上传日期"
            width="160">
            </el-table-column>
            <el-table-column
            prop="keywords"
            label="反对意见"
            width="180"
            class-name="keywords">
            </el-table-column>
            <el-table-column
            prop="article_type"
            label="类别"
            width="120">
            </el-table-column>
            <el-table-column
            prop="creator"
            label="上传人"
            width="120">
            </el-table-column>
            <el-table-column
            label="操作" width="120">
                <template slot-scope="scope">
                    <el-button style="color: red;" @click.stop="handleDelete(scope.row)" type="text" >刪除</el-button>
                    <a class="down-a" :href="'/api/baogao/' +scope.row.id +'/file/'" target="_blank">预览</a>
                </template>
            </el-table-column>
            </el-table>

            <el-pagination
            class="paganitionRight"
            @current-change="handleSizeChange"
            :page-size="10"
            :pager-count="9"
            layout="total, prev, pager, next"
            :total="totalCount">
            </el-pagination>
        </div>
    </div>
</template>
<script>
export default {
    name: 'reportDetailCommon',
    props: ['flag'],
    data () {
        return {
            checkList: [],
            cid:'',
            dialogVisible:false,
            contactWay: '',
            use: '', // 当前tab是哪个
            haskeyword: false,  // 投票建议有关键词， 风险治理研究没有有关键词
            hastype: false,  // 上传文件类型 投票有类型 风险治理没有类型
            options: [
                {
                value: '年度报告',
                label: '年度报告'
                }, 
                {
                value: '临时',
                label: '临时'
                }
            ],
            querydata:{
                search:'',
                article_type:'',
                start:'',
                end:'',
                page:1,
                use:''
            },
            pickerOptions2: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                    picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                    picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                    picker.$emit('pick', [start, end]);
                    }
                }]
            },
            tableData: [],
            totalCount: 0, // 总数据条数
            curIndex: 1, // 当前页面
            id: '',
            state: '',
            form: {
                name: '',
                type: '年度报告',
                keywords: []
            }
        }
    },
    updated () {
    },
    methods: {
        showAddDialog () {
            this.dialogVisible = true;

            this.$nextTick(()=>{
                this.$refs.uploadForm.reset()
            })
            this.form.name = '';
            this.form.type = '年度报告';
            this.form.keywords = [];
        },
        confirmsubmitFile(){
           this.$confirm('确认上传到 '+ this.form.type +' 分类, 是否继续?', '提示', {
                confirmButtonText: '继续',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.submitFile()
            }).catch(() => {
                
            })

        },
        submitFile () {
            let id = this.$route.query.id
            let formData = new FormData();
            let upfile = this.$refs.fileUp;
            const pattern = /.*\.pdf/i;
            if(!this.form.type){
                this.$message({
                    message: '请选择文章类型',
                    type:'info'
                });
                return false;
            }
            if(pattern.test(upfile.value)){
                formData.append("use", this.use);
                formData.append("article_name", this.form.name);
                formData.append("article_type", this.form.type);
                formData.append("keywords", this.form.keywords.join());
                formData.append("file", upfile.files[0]);

                this.$axios.post(`/api/com/${id}/baogao/`, formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                        'Authorization': localStorage.getItem('Authorization')
                    }
                })
                .then((res) => {
                    if (res.status === 201) {
                        this.$message('上传成功', 'success');
                        this.dialogVisible = false;
                        this.getReport();
                    }else{
                        this.$message({
                            message: '请完善上传信息',
                            type:'info'
                        });
                    }
                }).catch((error) => {
                    if(error.response.status === 400){
                        this.$message({
                            message: '请完善上传信息',
                            type:'info'
                        });
                    }else{
                        this.$message({
                            message: '上传失败请稍后再试，或联系管理员',
                            type:'error'
                        });
                    }
                    
                });
            }else{
                this.$message({
                    message: '只支持pdf文件文件上传',
                    type:'info'
                });
                return false;
            }

        },
        handleClose(done) {
            // this.$confirm('确认关闭？')
            // .then(_ => {
                done();
            // })
            // .catch(_ => {});
        },
        // 删除文章
        handleDelete(row){
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.delete(`/api/baogao/${row.id}/`)
                .then((res)=>{
                    if(res.status === 204){
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                    }
                    this.getReport();
                    
                }).catch((error)=>{
                    console.log(error);
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            })
        },
        handleSizeChange(val) {
            this.curIndex = val;
            this.getReport();
        },
        getReport(){
            let id = this.cid
            if (this.flag === '1') {
                this.use = '投票建议';
                this.getData(id);
            }else if (this.flag === '2') {
                this.use = '治理风险研究';
                this.getData(id);
            }
        },
        getData(id){
            this.$axios.get(`/api/com/${id}/baogao/`, {
                    params: {
                        use: this.use,
                        page: this.curIndex
                    }
                }).then(res => {
                    if(res.status === 200){
                        this.tableData = res.data.results;
                        this.totalCount = res.data.count;
                    }
                })
                .catch(error=>{
                    console.log(error);
                })
        },
        queryReport(page){
            console.log(this.querydata);
            let id = this.cid;
            if(page ===1){
                this.querydata['page'] = 1;
            }else{
                this.querydata['page'] = this.curIndex;
            }
            this.querydata['use'] = this.use;
            this.$axios.get(`/api/com/${id}/baogao/`,{
                params: this.querydata
            })
            .then((res)=>{
                console.log(res);
                if(res.status === 200 && res.data.results.length >0){
                        this.tableData = res.data.results;
                        this.totalCount = res.data.count;
                }else{
                    this.tableData = [];
                    this.totalCount = 0;
                }
            })
        },
        filechange(){
            let upfile = this.$refs.fileUp;
            const pattern = /.*\.pdf/i;
            console.log(upfile)
            if(pattern.test(upfile.value)){
                let temparray = upfile.value.split("\\");
                let filename = temparray[temparray.length-1].split('.')[0];
                this.form.name = filename;
            }else{
                // 非pdf文档提示
                this.$message({
                    message: '只支持pdf文件文件上传',
                    type:'info'
                });
                return false;
            }
        }
    },    
    mounted () {
        this.cid = this.$route.query.id;
        let id = this.cid
        if (this.flag === '1') {
            this.use = '投票建议';
            this.haskeyword = true;
            this.hastype = true;
            this.getData(id);
        }else if (this.flag === '2') {
            this.use = '治理风险研究';
            this.haskeyword = false;
            this.hastype = false;
            this.getData(id);
        }
            
    }
}
</script>
<style lang="scss" scoped>
.el-input {
    width: 170px!important;
}
.topMsg {
    padding: 10px 0;
}
.rightWay {
    float: right;
}
.el-checkbox {
    margin-right: 20px;
    width: 180px;
}
.down-a{
    text-decoration: none;
}
.el-table__body .keywords .cell{
    width: 16em;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
.keywords {
    color: red;
}
</style>
<style>
.el-table__body .keywords .cell{
    width: 12em;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
th.keywords{
    width: 13em;
}
</style>

